package com.foreveross.testproxy.test.impl;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.model.ProxyIpModel;
import com.foreveross.testproxy.test.IPTester;
import com.foreveross.testproxy.timer.RedisTianxunTimer;

/**
 * Created by Bright on 16/3/1.
 */
public class TianxunIPTestImpl implements IPTester {
	private static final Logger LOG = LoggerFactory.getLogger(TianxunIPTestImpl.class);
	
    /**
     * 代理IP天巡实现.
     *
     * @return
     */
    @Override
    public boolean test(ProxyIpModel proxy) {


    	DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = null;
		HttpRequestBase request = new HttpGet("http://www.tianxun.com/");
		if (proxy != null) {
		
			httpClient.getCredentialsProvider().getCredentials(
					new AuthScope(proxy.getIp(), proxy.getPort()));
			HttpHost httpHost = new HttpHost(proxy.getIp(), proxy.getPort());
			httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,httpHost);
		}
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
		request.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		request.setHeader("User-Agent",new IpConfigUtil().getUserAgent());

		try {

			response = httpClient.execute(request);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200 || code == 405) {
				return true;
			} else {
				//System.out.println("**** Ip:" + proxy.getIp() + "无效");
				return false;
			}
		} catch (Exception e) {
			LOG.error("**** Ip:" + proxy.getIp() + " 无效"+e.getMessage());
			 //e.printStackTrace();
			//System.out.println("**** Ip:" + proxy.getIp() + " 无效");
			return false;

		}
  }
}
